﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Configuration;

namespace Database
{
    /// <summary>
    /// 连接字符串
    /// </summary>
    internal static class ConnectionString
    {
        #region private variable
        private static string _ConnectionString;
        private static DbProviderFactory _dbProviderFactory;
        private static string _DbProviderClass;
        #endregion
        #region static properties
        public static DbProviderFactory dbProviderFactory
        {
            get { return _dbProviderFactory; }
        }
        public static string DbProviderClass
        {
            get { return _DbProviderClass; }
        }
        public static new string ToString
        {
            get { return _ConnectionString; }
        }
        #endregion
        #region static constractor
        static ConnectionString()
        {
            try
            {
                string ProviderName = ConfigurationManager.ConnectionStrings["EnableConfig"].ProviderName;
                string ConnectionString = ConfigurationManager.ConnectionStrings["EnableConfig"].ConnectionString;

                if (String.IsNullOrEmpty(ProviderName))
                    throw new Exception("数据库类型没有指定！");
                if (String.IsNullOrEmpty(ConnectionString))
                    throw new Exception("连接字符串不可用！");


                ProviderType ProviderValue;
                if (Enum.TryParse<ProviderType>(ProviderName, out ProviderValue) == false)
                {
                    if (String.IsNullOrEmpty(ProviderName))
                        throw new Exception("数据库类型有问题！");
                }
                _dbProviderFactory = DbProviderFactories.GetFactory(DbProviderAttribute.GetAttribute(ProviderValue).ProviderName);
                _DbProviderClass = DbProviderAttribute.GetAttribute(ProviderValue).ProviderClass;
                _ConnectionString = ConnectionString;
            }
            catch (DbException ex)
            {
                throw (ex);
            }
        }
        #endregion
    }
}
